<template>
  <div class="dc-container">
    <el-dialog v-model="visible" width="50%"
      :fullscreen="false" :title="title" :close-on-click-modal="false"
      @open="onDialogOpen" @close="onDialogClose">
      
      <el-form ref="editForm" :model="form" :rules="rules" label-width="100px" :disabled="mode == 'view'">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item prop="parent.id" label="父级">
              <el-cascader v-model="form.parent.id" :options="parentOptions"
                separator="/" placeholder="请选择父级" clearable filterable
                :props="{ label: 'name', value: 'id', children: 'children', checkStrictly: true, emitPath: false }"
                :style="{ width: '100%' }"></el-cascader>
            </el-form-item>
            
            <el-form-item prop="code" label="编号">
              <el-input v-model="form.code" maxLength="64" placeholder="请输入编号" clearable></el-input>
            </el-form-item>
            
            <el-form-item prop="name" label="名称">
              <el-input v-model="form.name" maxLength="128" placeholder="请输入名称" clearable></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item prop="url" label="URL">
              <el-input v-model="form.url" maxLength="128" placeholder="请输入URL" clearable></el-input>
            </el-form-item>
            
            <el-form-item prop="canPermission" label="可以授权">
              <el-switch v-model="form.canPermission" active-value="1" inactive-value="0"></el-switch>
            </el-form-item>
            
            <el-form-item prop="isLocked" label="禁用">
              <el-switch v-model="form.isLocked" active-value="1" inactive-value="0"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item prop="properties" label="扩展属性">
              <el-input v-model="form.properties" type="textarea" maxLength="1024" rows="3" placeholder="请输入扩展属性" clearable></el-input>
            </el-form-item>
            
            <el-form-item prop="remarks" label="备注信息">
              <el-input v-model="form.remarks" type="textarea" maxLength="255" rows="3" placeholder="请输入备注信息" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onSubmit" type="primary" v-show="mode != 'view'">保存</el-button>
          <el-button @click="onDialogClose" v-if="mode != 'view'">取消</el-button>
          <el-button @click="onDialogClose" v-if="mode == 'view'">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getRouterById, saveRouter, treeRouter } from '@/api/sys/router'
import BaseUI from '@/views/components/baseUI'

export default {
  extends: BaseUI,
  name: 'router-form',
  data() {
    return {
      mode: 'add',
      form: this.initForm(),
      visible: false,
      title: '路由表',
      
      rules: {
        'parent.id': [{ required: true, message: '父级不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        canPermission: [{ required: true, message: '可以授权不能为空', trigger: 'blur' }],
        isLocked: [{ required: true, message: '禁用不能为空', trigger: 'blur' }],
        properties: [{ required: true, message: '扩展属性不能为空', trigger: 'blur' }]
      },
      
      parentOptions: []
    }
  },
  props: {
    permission: {
      type: Object
    }
  },
  methods: {
    async onSubmit() {
      let validFlag = true

      await this.$refs.editForm.validate((valid) => {
        if (!valid) {
          validFlag = false
          return false
        }
      })

      if (validFlag) {
        this.doSave()
      }
    },
    doSave() {
      this.setLoad()
      saveRouter(this.form)
        .then((responseData) => {
          if (responseData.code == 100) {
            this.visible = false
            this.showMessage({
              type: 'success',
              msg: '保存成功'
            })
            this.$emit('save-finished')
          } else {
            this.showMessage(responseData)
          }
          this.resetLoad()
        })
        .catch((error) => {
          this.outputError(error)
        })
    },
    getFormById(id) {
      this.setLoad()
      return new Promise((resolve) => {
        getRouterById(id)
          .then((responseData) => {
            let form = {}
            if (responseData.code == 100) {
              form = responseData.data
            } else {
              this.showMessage(responseData)
            }
            this.resetLoad()
            resolve(form)
          })
          .catch((error) => {
            this.outputError(error)
          })
      })
    },
    onDialogClose() {
      this.visible = false
    },
    onDialogOpen() {
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    initForm() {
      return {
        parent: { id: '', name: '' },
        code: '',
        url: '',
        name: '',
        sort: 0,
        canPermission: '1',
        isLocked: '0',
        properties: '',
        remarks: ''
      }
    },
    async openView(id) {
      this.mode = 'view'
      this.title = `查看路由表`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions()
      this.visible = true
    },
    async openEdit(id) {
      this.mode = 'edit'
      this.title = `修改路由表`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions()
      this.visible = true
    },
    openAdd(parent) {
      this.mode = 'add'
      this.title = `添加路由表`
      this.form = this.initForm()
      
      if(parent) {
        this.form.parent.id = parent.id
      }

      this.initOptions()
      this.visible = true
    },
    async openCopy(id) {
      this.mode = 'add'
      this.title = `添加路由表`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions()
      this.form.id = null

      this.visible = true
    },
    
    initParentOptions() {
      let search_List = { params: [] }
      
      // 字段是parent_id,防止出现循环引用（子级不能成为自身或祖先的父级）
      if(this.form.id) {
        search_List.params.push.apply(search_List.params, [
          {
            columnName: 'router.ids',
            queryType: 'not like',
            value: this.form.id
          }
        ])
      }

      treeRouter(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.parentOptions = responseData.data
        } else {
          this.showMessage(responseData)
        }
      })
    },
    
    initOptions() {
      this.initParentOptions()
    }
  }
}
</script> 